package com.nuonuo.queue;

import com.nuonuo.config.RedissonUtils;
import com.nuonuo.listener.RedisDelayedQueueListener;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author duan
 * @version 1.0
 * @date 2024/1/25 16:53
 */
@Component
public class RedisDelayedQueue {



    @Resource(name = "primaryRedisson")
    RedissonUtils redissonUtils;


    /**
     * 描述: 添加队列
     *
     * @param t 数据
     * @param delay 延迟时间
     * @param timeUnit 延迟时间类型
     * @param queueName 队列名称
     * @return void
     * @author liufan
     * @date 2023-03-30
     */
    private <T> void addQueue(T t, long delay, TimeUnit timeUnit, String queueName) {
        RedissonClient redissonClient = redissonUtils.getRedissonClient();
        RBlockingQueue<T> blockingQueue = redissonClient.getBlockingQueue(queueName);
        RDelayedQueue<T> delayedQueue = redissonClient.getDelayedQueue(blockingQueue);
        delayedQueue.offer(t, delay, timeUnit);
    }


    /**
     * 描述:
     *
     * @param t
     * @param delay
     * @param clazz
     * @return void
     * @author liufan
     * @date 2023-03-30
     */
    public <T> void addQueueSeconds(T t, long delay, Class<? extends RedisDelayedQueueListener> clazz) {
        addQueue(t, delay, TimeUnit.SECONDS, clazz.getName());
    }

}
